package sever

import (
	"encoding/json"
	"errors"
	"fmt"
	"gitee.com/enjoy_5/sigin-rpc/internal/model"
	"gitee.com/enjoy_5/sigin-rpc/proto/clockin"
	"gitee.com/xuxinzhi2206/corehub/database/redis"
	"gorm.io/gorm"
	"strconv"
	"time"
)

// 创建签到的方法
func ClockInCreate(in *clockin.ClockInReq) (*model.Clocking, error) {
	stu := model.Clocking{
		UserId: in.UserId,
		Data:   time.Now(),
	}

	atoi := strconv.Itoa(int(stu.UserId))
	key := "record_true_" + atoi

	//获取签到记录
	record, err := stu.GetClockInfo()
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		fmt.Println("错误信息：：》", err)
		return nil, err
	}

	if record.ID == 0 {
		var res *model.Clocking
		fmt.Println("没有查询到数据>>创建新的签到记录")
		stu.Data = time.Now()
		stu.Status = 2
		res, err = stu.CreateClock()
		if err != nil {
			return nil, errors.New("创建新的签到记录失败")
		}
		m, _ := json.Marshal(res.Count)
		redis.SetRedis(key, string(m), time.Hour*24)
		return res, nil
	}
	//连续签到
	getRedis, _ := redis.GetRedis(key)
	if getRedis.Val() == "" {
		fmt.Println("没有连续签到记录>>去创建")
		upInfo, err := stu.UpdateClockIn()
		if err != nil {
			return nil, err
		}
		m, _ := json.Marshal(upInfo.Count)
		redis.SetRedis(key, string(m), time.Hour*24)
		fmt.Println("连续签到完成")
		return &upInfo, nil
	}
	fmt.Println("有签到记录")
	return nil, errors.New("今日已签到--不可重复签到")
}

// 获取签到详情的历史记录
func GetClock(in *clockin.GetClockInReq) ([]*model.Clocking, error) {
	res := model.Clocking{
		UserId: in.UserId,
	}
	stu, err := res.GetClockHistoryRecord()
	if err != nil {
		return nil, err
	}
	return stu, nil
}

// 补签
func RetroactiveClockIn(in *clockin.RetroactiveClockInReq) (*model.RetroactiveClocking, error) {
	res := model.RetroactiveClocking{
		UserId: in.UserId,
		Data:   time.Now(),
	}
	err := res.RetroactiveClockIn()
	if err != nil {
		return nil, err
	}
	return &res, nil
}

// 查询
func GetUserStatus(uid *clockin.GetClockInfoReq) (*clockin.Info, error) {
	c := model.Clocking{UserId: uid.UserId}
	infos, err := c.GetClockInfos()
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		return &clockin.Info{}, err
	}
	info := &clockin.Info{
		UserId: infos.UserId,
		Count:  infos.Count,
		Status: infos.Status,
	}
	return info, nil
}
